//
//  WKQcontroller.swift
//  mggz
//
//  Created by Apple on 2018/4/24.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import SVProgressHUD
import RxCocoa
import RxSwift

class WKQcontroller: UIViewController,UITableViewDelegate{

    @IBOutlet weak var monthlabel: UILabel!
    @IBOutlet weak var totalview: UITableView!
    @IBOutlet weak var detailview: UITableView!
    @IBOutlet weak var line: UIView!
    @IBOutlet weak var projectName: UILabel!
    var month,monthStr:String?
    var number:Int?
    var emptyview:EmptyView?
    
    var totaldatavariable:PublishSubject<[WKQTotalResult]> = PublishSubject()
    var selectDayvariable:PublishSubject<String> = PublishSubject()
    
    var detailvariable:PublishSubject<[WKQResult]> = PublishSubject()
    
    
    var isScroll:Bool = false
    
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        let img = UIColor.LightGreyBG.createImageWithColor()
        self.navigationController?.navigationBar.setBackgroundImage(img, for: .default)
        self.navigationController?.navigationBar.shadowImage = img
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.navigationBar.setBackgroundImage(UIColor.white.createImageWithColor(), for: .default)
        self.navigationController?.navigationBar.shadowImage = UIColor.gray.withAlphaComponent(0.5).createImageWithColor()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.title = "未考勤"
        self.projectName.text = ProjectName ?? ""
        self.monthlabel.text = self.monthStr
        self.totalview.register(UINib(nibName: "WKQItem", bundle: nil), forCellReuseIdentifier: "cell")
        self.totalview.tableFooterView = UIView(frame: .zero)
        self.totalview.backgroundColor = UIColor.LightGrey
        self.totalview.separatorStyle = .none
        self.totalview.bounces = false
        self.totaldatavariable.asObservable().bind(to: self.totalview.rx.items){
            (_,row,element) in
            let cell = self.totalview.dequeueReusableCell(withIdentifier: "cell", for: IndexPath(row : row, section : 0)) as! WKQItem
            cell.dataitem = element
            return cell
        }
        
        self.detailview.register(UINib(nibName: "WKQDetail", bundle: nil), forCellReuseIdentifier: "WKQDetail")
        self.detailview.tableFooterView = UIView(frame: .zero)
        self.detailview.bounces = false
        self.detailvariable.asObservable().bind(to: self.detailview.rx.items){
            (_,row,element) in
            let cell = self.detailview.dequeueReusableCell(withIdentifier: "WKQDetail", for: IndexPath(row : row, section : 0)) as! WKQDetail
            //cell.isScrollview = self.isScroll
            cell.dataitem = element
            cell.selectionStyle = .none
            print("\(self.isScroll)")
            
            return cell
        }
        
        self.selectDayvariable.subscribe { (day) in
            var timeutil = day.element
            timeutil!.removeSubrange(Range<String.Index>(NSMakeRange(10, (timeutil?.count)!-10), in: timeutil!)!)
            print("\(timeutil)")
            self.getTotalList(timeutil!)
            //getTotalList
        }
        
        
        self.totalview.rx.modelSelected(WKQTotalResult.self).subscribe { (event) in
            var day = event.element?.SignedDay!.timeYearAndMonth()
            print("\(day!)")
            SVProgressHUD.show(withStatus: "正在加载中")
            self.getTotalList(day!)
        }
        
        self.detailview.rx.modelSelected(WKQResult.self).subscribe{
            event in
            print("dianji")
            
            let mwDetail = MWDetailInfoViewController(nibName: "MWDetailInfoViewController", bundle: nil)
            
            mwDetail.DemandBaseMigrantWorkerID = event.element?.DemandBaseMigrantWorkerID ?? ""
            mwDetail.currentProjectName = ProjectName
            mwDetail.currentProjectId = ProjectId
            mwDetail.isZG = true
            mwDetail.LocateTime = ""
            //mwDetail.currentProject = selectedProject
            self.navigationController?.pushViewController(mwDetail, animated: true)
        }
        
        self.detailview.rx.itemSelected.subscribe{
            (event) in
            self.detailview.deselectRow(at: event.element!, animated: true)
            
            
            
            
        }
        
        //self.detailview.delegate = self
        
        SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.clear)
        
        if self.number == 0{
            self.addEmptyView("当月没有考勤数据")
        }else{
            self.getTotal()
        }
        
    }
    
    func getTotal(){
        SVProgressHUD.show(withStatus: "正在加载中")
        var params:[String:Any] = ["month":self.month!,"constructionProjectID":ProjectId as! String]
        MNetHttp.sharedInstance.postSingle(API_CALL_METHOD, method: .KaoQingTotal, params: &params, type: WKQTotal.self, success: { (bean,_) in
            guard let data = bean as? WKQTotal else{
                print("空数据")
                SVProgressHUD.dismiss()
                return
            }
            
            self.totaldatavariable.onNext(data.Result!)
            self.selectDayvariable.onNext((data.Result?.first?.SignedDay)!)
            self.totalview.selectRow(at: IndexPath(row: 0, section: 0), animated: false, scrollPosition: .top)
        }) { (error) in
            
            switch error{
            case .DATAERROR:
                self.addEmptyView("数据异常")
                break;
            case .DATAFAIL:
                break;
            case .HTTPERROR:
                self.addEmptyView("网络异常")
                break;
            case .StateFail(let obj):
                guard let data = obj as? [String:Any] else{
                    self.addEmptyView("网络异常")
                    return
                }
                self.addEmptyView(data["Msg"] as? String ?? "")
                break
            }
            SVProgressHUD.dismiss()
        }
    }
    
    func getTotalList(_ signedDay:String){
        var params:[String:Any] = ["signedDay":signedDay,"constructionProjectID":ProjectId as! String]
        MNetHttp.sharedInstance.postSingle(API_CALL_METHOD, method: .WKaoQingList, params: &params, type: WKQList.self, success: { (bean,_) in
            guard let data = bean as? WKQList else{
                
                return
            }
            
            self.detailvariable.onNext(data.Result!)
            self.detailview.scrollToRow(at: IndexPath(row: 0, section: 0), at: UITableViewScrollPosition.bottom, animated: true)
            SVProgressHUD.dismiss()
            
        }) { (error) in
            
            switch error{
            case .DATAERROR:
                self.addEmptyView("数据异常")
                break;
            case .DATAFAIL:
                break;
            case .HTTPERROR:
                self.addEmptyView("网络异常")
                break;
            case .StateFail(let obj):
                guard let data = obj as? [String:Any] else{
                    self.addEmptyView("网络异常")
                    return
                }
                self.addEmptyView(data["Msg"] as? String ?? "")
                break
            }
            SVProgressHUD.dismiss()
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func addEmptyView(_ status:String = "网络异常"){
        if self.emptyview != nil{
            self.emptyview?.removeFromSuperview()
            self.emptyview = nil
        }
        self.emptyview = EmptyView(frame: CGRect.zero, _title: status, _top: Float(ScreenHeight/5))
        self.view.addSubview(self.emptyview!)
        self.emptyview?.snp.updateConstraints({ (make) in
            make.top.equalTo(self.line.snp.bottom)
            make.left.equalTo(self.view.snp.left)
            make.right.equalTo(self.view.snp.right)
            make.bottom.equalTo(self.view.snp.bottom)
        })
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */
    
    func scrollViewDidScroll(_ scrollView: UIScrollView){
        //print("滚动")
        //self.isScroll = true
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView){
        //print("end")
        //self.isScroll = false
    }
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        //print("end")
        //self.isScroll = false
    }

}

